package com.gaff.emp.core.modules.auth.interceptor;


import cn.hutool.core.util.StrUtil;
import com.gaff.emp.core.EmpException;
import com.gaff.emp.core.modules.auth.JwtUtil;
import com.gaff.emp.core.modules.auth.LoginUserInfo;
import com.gaff.emp.core.modules.auth.annotation.Auth;
import com.gaff.emp.core.modules.perm.entity.SysMenu;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String USER_INFO_KEY = "Gaff-LoginUserInfo";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Auth annotation = null;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
        } else {
            return true;
        }

        // 从header中获取token
        String token = request.getHeader("gaff-token");
        // 如果header中不存在token，则从参数中获取token
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("gaff-token");
        }

        LoginUserInfo userInfo = JwtUtil.getUserInfoFromToken(token);
        if (userInfo != null) {
            request.setAttribute(USER_INFO_KEY, userInfo);
        }

        if (annotation == null) {
            return true;
        }

        // token为空
        if (StringUtils.isBlank(token)) {
            throw new EmpException(HttpStatus.UNAUTHORIZED.value(), "非法访问");
        }

        if (userInfo == null) {
            throw new EmpException(HttpStatus.UNAUTHORIZED.value(), "登录已过期");
        }

        String perm = annotation.perm();
        if (!StrUtil.isNotBlank(perm)) {
            return true;
        }
        if (!checkPerm(userInfo.getMenus(), perm)) {
            throw new EmpException(HttpStatus.FORBIDDEN.value(), "没有访问权限");
        }

        return true;
    }

    private boolean checkPerm(List<SysMenu> menus, String perm) {
        if (menus.size() == 0) {
            return false;
        }
        SysMenu menu = menus.get(0);
        if (menu.getSubMenus() != null && menu.getSubMenus().size() > 0) {
            for (SysMenu subMenu : menu.getSubMenus()) {
                if (StrUtil.isNotBlank(subMenu.getPerm()) && perm.equals(subMenu.getPerm())) {
                    return true;
                }
            }
        } else if (StrUtil.isNotBlank(menu.getPerm()) && perm.equals(menu.getPerm())) {
            return true;
        }
        return checkPerm(menus.subList(1, menus.size()), perm);
    }

}
